<?php

class base_pdomysql {

    public $connected = FALSE;

    public $mConn;
    protected $DbUserName, $DbPassWord, $DbConnectStr, $DbCharset;

    public static $_instance = array();

    private function __construct($type = 0, $autoClose = 0, $ociDbServer = array(), $ociConnectStr = "") {
    	if($GLOBALS['online']){
    		$host = '172.16.17.201';
    		$dbname = 'appcms';
    		$user = 'appcms';
    		$password = 'QDDciE6uro3hZqiTqU4T';
    	}else{
    		$host = '172.16.10.28';
    		$dbname = 'mobileappcms.wanlitong.com_test';
    		$user = 'wlt_cms_test';
    		$password = 'pajk12345!@#$%';
    	}

        try {
            $this -> mConn = new PDO("mysql:host=$host;dbname=$dbname", $user, $password, array(
                PDO::ATTR_PERSISTENT => $type,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
                PDO::ATTR_AUTOCOMMIT => TRUE
            ));
            $this -> connected = TRUE;
        } catch ( Exception $e ) {
            printf($e -> getMessage());
            exit();
        }

        if ($autoClose) {
            register_shutdown_function(array(
                &$this,
                'close_pdooci'
            ));
        }
    }

    private function __clone() {
    }

    public static function connect($force = false, $autoClose = 0, $ociDbServer = array(), $ociConnectStr = "") {
        $arrStr = md5(json_encode((array)($ociDbServer)));
        if (empty(self::$_instance) || !(self::$_instance[$arrStr] instanceof self) || $force) {
            self::$_instance[$arrStr] = new self($type, $autoClose, $ociDbServer, $ociConnectStr);
        }
        return self::$_instance[$arrStr];
    }

    public function close_pdooci() {
        $this -> mConn = null;
    }

}

class model_base {
    public static function DB() {
        $pdo = base_pdomysql::connect();
        $conn = $pdo -> mConn;
        if(!self::check_ping($conn)){
        	$pdo->close_pdooci();
        	$pdo = base_pdomysql::connect(true);
        	$conn = $pdo -> mConn;
        }
        return $conn;
    }

    public static function returnLimit($page, $rows) {
        $start = ($page * $rows) - $rows;
        return " limit $start,$rows";
    }
    
    public static function check_ping($link){
    	$status = $link->getAttribute(PDO::ATTR_SERVER_INFO);
        if(strpos($status,'MySQL server has gone away')!==false){
            return false;
        }
        return true;
    }

}
?>